package com.tzy.note.base.thread.create;

/**
 * 实现Runnable接口多线程模拟龟兔赛跑
 */
public class CreateThread2_GTRace implements Runnable {
    //胜利者
    private static String winner;

    private int stepsMax = 100;
    @Override
    public void run(){
        for (int i = 1; i <= stepsMax; i++) {
            //模拟兔子每10步睡一觉
            if("兔子".equals(Thread.currentThread().getName()) && i%10 == 0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //判断出赛是否结束
            boolean flag = this.gameOver(i);
            //如果出赛结束.就停止程序
            if(flag){
                break;
            }
            System.out.println(Thread.currentThread().getName() + "-->跑包" + i +"步");
        }
    }
    //判断是否完成比赛
    private boolean gameOver(int steps){
        //判断是否有胜利者
        if(winner != null){ //己经存在胜利者了
            return true;
        }else{
            if(steps == stepsMax){
                winner = Thread.currentThread().getName();
                System.out.println("winner is " + winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        CreateThread2_GTRace race = new CreateThread2_GTRace();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}
